<template>
	<u-upload
			ref="upload"
			:useBeforeRead="true"
			@beforeRead="beforeRead"
			@afterRead="afterRead"
			:maxSize="2 * 1024 * 1024"
			:maxCount="1"
			name="head"
			width="0"
			height="0"
		>
		<!-- <image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" 
	mode="widthFix" style="width: 250px;height: 150px;"></image> -->
		<u-image :src="vuex_user.avatar_url ? vuex_user.avatar_url : '/static/logo.png'" width="50px" height="50px" shape="circle">
		</u-image>
	</u-upload>
</template>

<script>
	let _this={};
	export default {
		name:"oss-upload",
		data() {
			return {
				formData: {}, //定义一个接受文件和表单信息
				tokenUrl:"",
			};
		},
		methods:{
			// 上传前的处理 在小程序中如过用this，可能this会丢失，所以建议使用uni
			async beforeRead(event){
				console.log("beforeRead");
				//上传到oss之前需要先获取token
				const ossToken =await uni.$u.api.authOsstoken();
				uni.$u.tokenUrl = ossToken.host;
				uni.$u.formData={
					'key' : event.name+'.png', //上传后的文件名
					'policy': ossToken.policy, //策略
					'OSSAccessKeyId': ossToken.accessid, //oss的accesskey 
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					'signature': ossToken.signature,  //签名
				};
				// console.log(uni.$u.formData);
				return true;
			},
		
			// 新增图片
			async afterRead(event) {
				setTimeout( async ()=>{ //这里之所以要暂停一秒，是因为beforeRead中的数据还没处理完，就执行afterRead，会有参数没有完成赋值
					let lists = [].concat(event.file);
					for (let i = 0; i < lists.length; i++) {
						const result = await _this.uploadFilePromise(lists[i].thumb);
					}
				},1000);
			},
			uploadFilePromise(url) {
				// console.log(url);
				// console.log(uni.$u.formData);
				const name = uni.$u.formData.key;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.$u.tokenUrl, // 仅为示例，非真实的接口地址
						filePath: url,
						name: name,
						formData: uni.$u.formData,
						success: async (res) => {
							// uni.$u.$refs.upload.remove(0); //移除原来的头像
							//请求API更新头像
							const data = await uni.$u.api.updateAvatar({"avatar": uni.$u.formData.key});
							//更新缓存
							uni.$u.utils.updateUser();
							
							uni.$u.toast('更新成功');
						},
						fail: (res) => {
							console.log(res);
						}
					});
				})
			},
		},created() {
			_this = this;
		}
	}
</script>

<style lang="scss" scoped>

</style>
